package com.dong.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dong.service.UserService;
import com.dong.util.Empty;

public class LoginServlet extends HttpServlet {
	
	private static final long serialVersionUID = 5136044242554674454L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		
		/**
		 * 本方法用于用户登录验证
		 */
		String message = "";
		
		//获取客户端的用户名，用户密码
		String uid = request.getParameter("uid");
		String password = request.getParameter("password");
		//服务器端的验证
		if(Empty.isEmpty(uid) || Empty.isEmpty(password)) {
			//用户名或密码为空，重新转向登录界面
			message = "登录失败！对不起，用户名或密码不能为空，请重新输入!";
			request.setAttribute("message", message);
			request.getRequestDispatcher("userLogin.jsp").forward(request, response);
		} else {
			//用户名和密码不为空,查询数据库进行验证
			UserService userService = new UserService();
			//UserService的login方法抛出异常，需catch exception
			try {
				boolean flag = userService.login(uid, password);
				if (flag) {
					//flag为true，表明登录成功,转向登录成功页面
					message = "恭喜您,登录成功！";
					request.setAttribute("message", message);
					request.getRequestDispatcher("/userLoginSuc.jsp").forward(request, response);
				} else {
					//flag为false，表明用户名或密码错误，重新转向登录界面
					message = "登录失败！用户名或密码错误，请确认后重新输入！";
					request.setAttribute("message", message);
					request.getRequestDispatcher("userLogin.jsp").forward(request, response);
				}
			} catch (Exception e) {
				e.printStackTrace();
				//异常发生，转向错误页面
				message = "服务器内部发生错误，请重试！";
				request.setAttribute("message", message);
				request.getRequestDispatcher("error.jsp").forward(request, response);
			}
		}		
	}
}
